package mil.af.amc.adpetracker.web.actions.struts1;

import mil.af.amc.adpetracker.service.AccountService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Action class to register a new account
 *
 * @author TSgt Jason Ferguson
 * @author SrA Schevus Osborne
 */
public class RegisterAction extends AbstractAction {

    private static final Log log = LogFactory.getLog(RegisterAction.class);

    private AccountService accountService;

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {

        DynaActionForm accountForm = (DynaActionForm) form;
                                         
        try {
            accountService.createAccount(accountForm.getMap());
        } catch (Exception e) {
            ActionMessage actionMessage = new ActionMessage("error.register.duplicate-username", "Username already exists");
            saveError(request, actionMessage);
            log.debug("Unable to create account for username: " + accountForm.get("email"), e);

            return mapping.getInputForward();
        }

        ActionMessage msg = new ActionMessage("Account created. Please check your email.");
        saveError(request, msg);

        log.info("Created account for username: " + accountForm.get("email"));

        return mapping.findForward("success");
    }
}
